package com.lib.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import java.io.File;
import java.util.List;


/**
 * [从本地选择图片以及拍照工具类，完美适配2.0-5.0版本]
 **/
public class PhotoHelper {
    /* 拍照成功后返回 */
    public static final int INTENT_TAKE = 1;
    /* 选择成功后返回 */
    public static final int INTENT_SELECT = 2;
    /* 裁剪图片成功后返回 */
    public static final int INTENT_CROP = 3;

    private int mAspectX = 1;
    private int mAspectY = 1;
    private int mCropW = 256;
    private int mCropH = 256;

    private boolean mNeedCrop = true;
    private OnPhotoResultListener onPhotoResultListener;

    public PhotoHelper setOnPhotoResultListener(OnPhotoResultListener onPhotoResultListener) {
        this.onPhotoResultListener = onPhotoResultListener;
        return this;
    }

    public PhotoHelper setNeedCrop(boolean needCrop) {
        mNeedCrop = needCrop;
        return this;
    }

    public PhotoHelper setSize(int aspectX, int aspectY, int cropW, int cropH) {
        mAspectX = aspectX;
        mAspectY = aspectY;
        mCropW = cropW;
        mCropH = cropH;
        return this;
    }

    /**
     * 拍照
     *
     * @param
     * @return
     */
    public void takePicture(Activity activity) {
        //每次选择图片吧之前的图片删除
        clearCropFile(buildUri(activity));
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, buildUri(activity));
            if (!isIntentAvailable(activity, intent)) {
                return;
            }
            activity.startActivityForResult(intent, INTENT_TAKE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 选择一张图片
     * 图片类型，这里是image/*，当然也可以设置限制
     * 如：image/jpeg等
     *
     * @param activity Activity
     */
    @SuppressLint("InlinedApi")
    public void selectPicture(Activity activity) {
        //每次选择图片吧之前的图片删除
        clearCropFile(buildUri(activity));
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

            if (!isIntentAvailable(activity, intent)) {
                return;
            }
            activity.startActivityForResult(intent, INTENT_SELECT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建uri
     *
     * @param activity
     * @return
     */
    private Uri buildUri(Activity activity) {
        String cropFileName = "crop_file.jpg";
        boolean checkSDCard = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
        if (checkSDCard) {
            return Uri.fromFile(Environment.getExternalStorageDirectory()).buildUpon().appendPath(cropFileName).build();
        } else {
            return Uri.fromFile(activity.getCacheDir()).buildUpon().appendPath(cropFileName).build();
        }
    }

    /**
     * @param intent
     * @return
     */
    public boolean isIntentAvailable(Activity activity, Intent intent) {
        PackageManager packageManager = activity.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private boolean corp(Activity activity, Uri uri) {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(uri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", mAspectX);
        cropIntent.putExtra("aspectY", mAspectY);
        cropIntent.putExtra("outputX", mCropW);
        cropIntent.putExtra("outputY", mCropH);
        cropIntent.putExtra("return-data", false);
        cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        Uri cropuri = buildUri(activity);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropuri);
        if (!isIntentAvailable(activity, cropIntent)) {
            return false;
        } else {
            try {
                activity.startActivityForResult(cropIntent, INTENT_CROP);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (onPhotoResultListener == null) {
            return;
        }
        if (resultCode != Activity.RESULT_OK) {
            onPhotoResultListener.onCancel();
            return;
        }
        Uri uri = buildUri(activity);
        if (uri == null) {
            return;
        }
        switch (requestCode) { /*拍照*/
            case INTENT_TAKE: {
                if (!mNeedCrop) {
                    returnPath(activity, data);
                    return;
                }
                boolean corp = corp(activity, uri);
                if (corp) {
                    return;
                }
                onPhotoResultListener.onCancel();
            }
            break;
            case INTENT_SELECT: { /*选择图片*/
                if (data != null) {
                    Uri imageUri = data.getData();
                    if (imageUri != null) {
                        if (!mNeedCrop) {
                            returnPath(activity, data);
                            return;
                        }
                        boolean corp = corp(activity, imageUri);
                        if (corp) {
                            return;
                        }
                    }
                }
                onPhotoResultListener.onCancel();
            }
            break;
            case INTENT_CROP:/*截图*/
                String path = uri.getPath();
                onPhotoResultListener.onPhotoResult(path);
                break;
        }
    }

    private void returnPath(Activity activity, Intent data) {
        try {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            onPhotoResultListener.onPhotoResult(picturePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param uri
     * @return
     */
    private boolean clearCropFile(Uri uri) {
        if (uri == null) {
            return false;
        }

        String path = uri.getPath();
        if (path == null) {
            return false;
        }
        File file = new File(path);
        if (file.exists()) {
            boolean result = file.delete();
            if (result) {
                XLog.i("Cached crop file cleared.");
            } else {
                XLog.e("Failed to clear cached crop file.");
            }
            return result;
        }
        return false;
    }

    /**
     * [回调监听类]
     *
     * @author huxinwu
     * @version 1.0
     * @date 2015-1-7
     **/
    public interface OnPhotoResultListener {
        void onPhotoResult(String path);

        void onCancel();
    }
}
